#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
提示词生成器配置管理模块

该模块负责管理提示词生成器的各项配置参数，包括生成引擎配置、优化器配置等。
"""

import json
import os
from typing import Dict, Any, Optional


class PromptGeneratorConfig:
    """
    提示词生成器配置类
    
    管理提示词生成器的所有配置参数
    """
    
    # 默认配置
    DEFAULT_CONFIG = {
        "generation_engine": {
            "template_dir": "src/config/prompt_templates.json",
            "max_tokens": 1000,
            "temperature": 0.7
        },
        "optimizer": {
            "min_length": 50,
            "max_length": 500,
            "keyword_weight": 0.4,
            "clarity_weight": 0.4,
            "length_weight": 0.2
        },
        "information_fusion": {
            "sample_data_path": "cache/sample_data.json",
            "max_samples": 100
        }
    }
    
    _instance: Optional['PromptGeneratorConfig'] = None
    
    def __new__(cls):
        """
        单例模式创建实例
        """
        if cls._instance is None:
            cls._instance = super(PromptGeneratorConfig, cls).__new__(cls)
            cls._instance._initialize()
        return cls._instance
    
    def _initialize(self):
        """
        初始化配置
        """
        self._config = self.DEFAULT_CONFIG.copy()
        self._config_path = None
    
    def load_config(self, config_path: Optional[str] = None) -> None:
        """
        从配置文件加载配置
        
        Args:
            config_path: 配置文件路径
        """
        if config_path and os.path.exists(config_path):
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    loaded_config = json.load(f)
                    self._update_config(loaded_config)
                self._config_path = config_path
            except (json.JSONDecodeError, IOError) as e:
                print(f"警告: 无法加载配置文件 {config_path}: {str(e)}")
    
    def _update_config(self, new_config: Dict[str, Any]) -> None:
        """
        更新配置
        
        Args:
            new_config: 新的配置字典
        """
        for key, value in new_config.items():
            if key in self._config and isinstance(self._config[key], dict) and isinstance(value, dict):
                self._config[key].update(value)
            else:
                self._config[key] = value
    
    def get(self, key_path: str, default: Any = None) -> Any:
        """
        获取配置值
        
        Args:
            key_path: 配置键路径，使用点号分隔，如 "generation_engine.max_tokens"
            default: 默认值
            
        Returns:
            配置值或默认值
        """
        keys = key_path.split('.')
        value = self._config
        
        for key in keys:
            if isinstance(value, dict) and key in value:
                value = value[key]
            else:
                return default
        
        return value
    
    def set(self, key_path: str, value: Any) -> None:
        """
        设置配置值
        
        Args:
            key_path: 配置键路径，使用点号分隔
            value: 新的配置值
        """
        keys = key_path.split('.')
        config = self._config
        
        # 遍历到倒数第二个键
        for key in keys[:-1]:
            if key not in config or not isinstance(config[key], dict):
                config[key] = {}
            config = config[key]
        
        # 设置最终的值
        config[keys[-1]] = value
    
    def save_config(self, config_path: Optional[str] = None) -> bool:
        """
        保存配置到文件
        
        Args:
            config_path: 配置文件路径，默认为加载时的路径
            
        Returns:
            是否保存成功
        """
        save_path = config_path or self._config_path
        if not save_path:
            return False
        
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(os.path.abspath(save_path)), exist_ok=True)
            
            with open(save_path, 'w', encoding='utf-8') as f:
                json.dump(self._config, f, ensure_ascii=False, indent=2)
            return True
        except IOError as e:
            print(f"警告: 无法保存配置文件 {save_path}: {str(e)}")
            return False
    
    def get_full_config(self) -> Dict[str, Any]:
        """
        获取完整配置
        
        Returns:
            完整配置字典
        """
        return self._config.copy()


def get_prompt_generator_config() -> PromptGeneratorConfig:
    """
    获取提示词生成器配置实例
    
    Returns:
        PromptGeneratorConfig 实例
    """
    return PromptGeneratorConfig()


if __name__ == "__main__":
    # 测试配置管理器
    config = get_prompt_generator_config()
    
    # 获取默认配置
    print("默认配置:")
    print(f"生成引擎最大token数: {config.get('generation_engine.max_tokens')}")
    print(f"优化器最小长度: {config.get('optimizer.min_length')}")
    print(f"信息融合最大样本数: {config.get('information_fusion.max_samples')}")
    
    # 修改配置
    config.set('generation_engine.temperature', 0.8)
    print(f"修改后的温度参数: {config.get('generation_engine.temperature')}")
    
    # 测试获取不存在的配置
    print(f"不存在的配置: {config.get('non_existent.key', '默认值')}")
    
    print("配置管理器测试完成!")